package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.1.11:3306)/gorm_test?charset=utf8mb4&parseTime=True&loc=Local"

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: true,        // Ignore ErrRecordNotFound error for logger
			Colorful:                  true,        // Disable color
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}

	email := "binsoft@163.com"
	//db.AutoMigrate(&User{})
	db.Create(&User{Name: "binsoft", Email: &email})
	// UPDATE `users` SET `name`='',`updated_at`='2021-06-27 20:51:01.864' WHERE `id` = 1
	db.Model(&User{ID: 1}).Update("Name", "")
	//UPDATE `users` SET `updated_at`='2021-06-27 20:53:07.756' WHERE `id` = 2
	db.Model(&User{ID: 2}).Updates(User{Name: ""})
	//Updates 语句不会更新零值，但是update语句会更新零值

	emptyEmail := ""
	//UPDATE `users` SET `email`='',`updated_at`='2021-06-27 20:56:24.654' WHERE `id` = 4
	db.Model(&User{ID: 4}).Updates(User{Email: &emptyEmail})

	/*
			解决仅更新非零值字段的方法有两种：
		1. 将string 设置为 *string
		2. 使用sql的NULLXXX类型来解决
	*/

	user2 := &User{Name: "彬少"}
	result := db.Create(&user2)

	fmt.Println(user2.ID)
	fmt.Println(result.Error)
	fmt.Println(result.RowsAffected)

}
